<template>
    <view class="pg">
        <wd-form ref="form" :model="model">
            <wd-cell-group border>
                <wd-input
                    size="large"
                    label="名称"
                    label-width="100px"
                    prop="name"
                    clearable
                    v-model="model.name"
                    placeholder="模板名称"
                    :rules="[{ required: true, message: '请填写模板名称' }]"
                />
                <wd-input
                    size="large"
                    label="电话"
                    label-width="100px"
                    prop="phone"
                    clearable
                    v-model="model.phone"
                    placeholder="管理员电话"
                    :rules="[{ required: true, pattern: /\d{11}/, message: '请正确填写管理员电话' }]"
                />
            </wd-cell-group>

            <!-- 货架商品管理 -->
            <wd-divider>货架商品</wd-divider>
            <wd-cell-group border v-for="(item, index) in model.goodsList" :key="index">
                <title-block :title="'商品' + (index + 1)" transparent></title-block>
                <wd-picker
                    size="large"
                    title="商品名称"
                    label="商品名称"
                    value-key="machineGoodsId"
                    label-key="name"
                    placeholder="请选择产品"
                    label-width="100px"
                    :prop="'goodsList.' + index + '.machineGoodsId'"
                    v-model="item.machineGoodsId"
                    :columns="index == 0 ? goodsList1 : goodsList2"
                    :rules="[{ required: true, message: '请选择商品' }]"
                />
                <wd-cell size="large" required title="货道" title-width="64px" center>
                    <wd-radio-group
                        :prop="'goodsList.' + index + '.position'"
                        v-model="item.position"
                        shape="button"
                        line
                        @change="select_position(item.position, index)"
                        :rules="[{ required: true, message: '请选择商品货道' }]"
                    >
                        <wd-radio v-if="index == 0" :value="5">5</wd-radio>
                        <template v-else>
                            <wd-radio :value="1">1</wd-radio>
                            <wd-radio :value="2">2</wd-radio>
                            <wd-radio :value="3">3</wd-radio>
                            <wd-radio :value="4">4</wd-radio>
                        </template>
                    </wd-radio-group>
                </wd-cell>
                <wd-cell></wd-cell>
            </wd-cell-group>
            <wd-cell-group border>
                <wd-cell title="" center>
                    <wd-button size="small" type="info" plain custom-class="mr-10" @click="add_goods">添加</wd-button>
                    <wd-button v-if="model.goodsList.length - 1" size="small" type="error" plain @click="del_goods">删除</wd-button>
                </wd-cell>
            </wd-cell-group>

            <!-- 充电套餐管理 -->
            <wd-divider>充电套餐</wd-divider>
            <wd-cell-group border v-for="(item, index) in model.chargingList" :key="index">
                <title-block :title="'套餐' + (index + 1)" transparent></title-block>
                <wd-input
                    size="large"
                    label="名称"
                    label-width="100px"
                    :prop="'chargingList.' + index + '.name'"
                    clearable
                    v-model="item.name"
                    placeholder="套餐名称"
                    :rules="[{ required: true, message: '请填写套餐名称' }]"
                />
                <wd-picker
                    size="large"
                    required
                    label="时长(分钟)"
                    title="时长(分钟)"
                    placeholder="请选择充电时长"
                    label-width="100px"
                    :prop="'chargingList.' + index + '.min'"
                    v-model="item.min"
                    :columns="chargeMin"
                    :rules="[{ required: true, message: '请选择充电时长' }]"
                />
                <wd-input
                    size="large"
                    label="价格(元)"
                    label-width="100px"
                    :prop="'chargingList.' + index + '.price'"
                    clearable
                    v-model="item.price"
                    placeholder="套餐价格"
                    :rules="[
                        { required: true, message: '请填写套餐价格' },
                        { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入有效的数字，最多两位小数' }
                    ]"
                />
                <wd-cell></wd-cell>
            </wd-cell-group>
            <wd-cell-group border>
                <wd-cell title="" center>
                    <wd-button size="small" type="info" plain custom-class="mr-10" @click="add_charge">添加</wd-button>
                    <wd-button v-if="model.chargingList.length - 1" size="small" type="error" plain @click="del_charge">删除</wd-button>
                </wd-cell>
                <wd-button size="large" type="primary" custom-class="w-700 m-10-0-10-25" @click="handleSubmit">提交</wd-button>
            </wd-cell-group>
        </wd-form>
    </view>
</template>

<script setup>
    import { reactive, ref } from 'vue';
    import { onLoad } from '@dcloudio/uni-app';
    import { api_goods_list } from '@/api/goods.js';
    import { api_machineOption_save } from '@/api/machineOption.js';
    import { number } from '../../../../../uni_modules/uview-plus/libs/function/test';

    const form = ref(null);

    // 模型数据
    const model = reactive({
        name: '',
        phone: '',
        goodsList: [
            {
                machineGoodsId: '',
                position: ''
            }
        ],
        chargingList: [
            {
                name: '',
                min: '',
                price: ''
            }
        ],
        selectedPositions: [] // 用于存储已选择的货道位置
    });

    // 商品选择器列表
    const goodsList1 = ref([]); //纸巾
    const goodsList2 = ref([]); //正常商品

    // 充电时长选择器列表
    const chargeMin = ref(
        Array.from({ length: 60 }, (_, index) => ({
            value: index + 1,
            label: index + 1
        }))
    );

    onLoad(async () => {
        //加载商品
        try {
            //纸巾
            let res1 = await api_goods_list({
                pagecut: false,
                queryMap: {
                    eq: { type: 2 },
                    order: { create_time: 'desc' }
                }
            });
            //只保留id和name,再把id改成machineGoodsId
            goodsList1.value = res1.data.map(({ id, name }) => ({ id, name })).map(({ id, ...rest }) => ({ machineGoodsId: id, ...rest }));

            //正常商品
            let res2 = await api_goods_list({
                pagecut: false,
                queryMap: {
                    eq: { type: 0 },
                    order: { create_time: 'desc' }
                }
            });
            //只保留id和name,再把id改成machineGoodsId
            goodsList2.value = res2.data.map(({ id, name }) => ({ id, name })).map(({ id, ...rest }) => ({ machineGoodsId: id, ...rest }));
        } catch (error) {
            uni.showToast({
                title: error.msg,
                icon: 'none'
            });
        }
    });

    // 点击添加商品
    const add_goods = () => {
        if (model.goodsList.length < 4) {
            model.goodsList.push({
                machineGoodsId: '',
                position: ''
            });
        } else {
            uni.showToast({
                title: '已达到最大数量(4个)',
                icon: 'error'
            });
            return;
        }
    };

    // 点击删除商品
    const del_goods = () => {
        if (model.goodsList.length > 0) {
            let removedPosition = model.goodsList.pop().position;
            if (removedPosition) {
                model.selectedPositions = model.selectedPositions.filter((pos) => pos !== removedPosition);
            }
        }
    };

    // 选择货道
    const select_position = (position, index) => {
        if (position) {
            model.selectedPositions[index] = position; // 更新已选择的货道位置
        }
    };

    // 点击添加充电套餐
    const add_charge = () => {
        model.chargingList.push({
            id: '',
            name: '',
            min: '',
            price: ''
        });
    };

    // 点击删除充电套餐
    const del_charge = () => {
        if (model.chargingList.length > 1) {
            model.chargingList.pop();
        }
    };

    // 提交表单
    const handleSubmit = async () => {
        // 收集所有货道位置
        let positions = model.goodsList.map((item) => item.position).filter((pos) => pos !== '');

        // 检查是否有重复的货道位置
        let uniquePositions = new Set(positions);
        if (positions.length !== uniquePositions.size) {
            uni.showToast({
                title: '重复货道',
                icon: 'error'
            });
            return;
        }

        // 执行表单验证
        try {
            let { valid, errors } = await form.value.validate();

            // 表单验证通过
            if (valid) {
                uni.showModal({
                    title: '是否提交',
                    success: async (res) => {
                        if (res.confirm) {
                            model.chargingList.map((item) => ({
                                ...item,
                                price: number(item.price)
                            }));
                            // 访问添加接口;
                            // let param;
                            try {
                                let res = await api_machineOption_save(model);
                                uni.showToast({
                                    title: res.msg,
                                    icon: 'success',
                                    success: () => {
                                        uni.navigateBack();
                                    }
                                });
                            } catch (error) {
                                uni.showToast({
                                    title: error.msg,
                                    icon: 'none'
                                });
                            }
                        }
                    }
                });

                console.log(model);
            } else {
                console.log('校验失败', errors);
            }
        } catch (error) {
            // 表单验证失败或发生其他错误
            console.error('错误', error);
        }
    };
</script>

<style lang="scss" scoped>
    /* 你可以在这里添加样式 */
</style>
